package analyse

import (
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/model/paylog"
	"sg-backend/utils"
	"strconv"
	"time"
)

// 根据传入的年份，获取每个月的收入，支出汇总数据，展示条形图

func GetThisYearPayAndIncomeData(ctx *fiber.Ctx) error {
	// 年度
	year := ctx.QueryInt("year", time.Now().Year())

	monthList := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

	// X轴
	xData := []any{"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"}

	// 支出Y轴
	var yData1 []any
	for _, v := range monthList {
		// 按年份，月份，计算每个月的起止时间
		startTime := strconv.Itoa(year) + "-" + strconv.Itoa(v) + "-1 00:00:00"
		monthHaveDays := utils.GetYearMonthToDay(year, v)
		endTime := strconv.Itoa(year) + "-" + strconv.Itoa(v) + "-" + strconv.Itoa(monthHaveDays) + " 23:59:59"
		var paymentLog []paylog.PayLog
		if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
			Where("time >= ? AND time <= ?", startTime, endTime).
			Find(&paymentLog); err.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "获取年度支出数据出错！" + err.Error.Error(),
			})
		}

		// 汇总
		var total = float64(0)
		for _, x := range paymentLog {
			total = total + x.Money - x.Refund // 减去退款才是真的支出
		}
		total = utils.NumberToStr(total)
		yData1 = append(yData1, total)
	}

	// 收入Y轴
	var yData2 []any
	for _, v := range monthList {
		// 按年份，月份，计算每个月的起止时间
		startTime := strconv.Itoa(year) + "-" + strconv.Itoa(v) + "-1 00:00:00"
		monthHaveDays := utils.GetYearMonthToDay(year, v)
		endTime := strconv.Itoa(year) + "-" + strconv.Itoa(v) + "-" + strconv.Itoa(monthHaveDays) + " 23:59:59"
		var incomeLog []paylog.IncomeLog
		if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
			Where("time >= ? AND time <= ?", startTime, endTime).
			Find(&incomeLog); err.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "获取年度收入数据出错！" + err.Error.Error(),
			})
		}

		// 汇总
		var total = float64(0)
		for _, x := range incomeLog {
			total = total + x.Money
		}
		total = utils.NumberToStr(total)
		yData2 = append(yData2, total)
	}

	return ctx.JSON(fiber.Map{
		"status": "done",
		"data": _dataJson{
			XData:  xData,
			YData1: yData1,
			YData2: yData2,
		},
	})
}
